import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
  
      /**
       * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
       * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
       */
        const res = response.data;
        const headers = response.headers;
        if(headers.token!=undefined||headers.token==""){
          setToken(headers.token);
        }
       if (res.code === 401 || res.code === 40101){
          MessageBox.alert('你已被登出，请重新登录', '确定登出', {
          confirmButtonText: '确定',
          callback: action => {
            store.dispatch('FedLogOut').then(() => {
              location.reload(); // 为了重新实例化vue-router对象 避免bug
            });
          }
        });
         return Promise.reject('error');
      }
      if (res.code === 60203) {
        Message({
          message: '当前用户无相关操作权限！',
          type: 'error',
          duration: 5 * 1000
        });
        return Promise.reject('error');
      }
      if (response.code === 500) {
        Message({
          message: "服务器开小差了！请联系客服。",
          type: 'error',
          duration: 5 * 1000
        });
      } else {
        return response.data;
      }
    },
    error => {
      Message({
        message: "服务器开小差了！请联系客服。",
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject(error);
    }
)

export default service
